﻿using Kingdee.BOS.App.Core;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using RestSharp;
using RK.Model.Ronma;
using RK.Tools;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace RK.SerivesPlugin.Ronma
{
    [Description("金蝶同步WMS通用服务插件")]
    [HotUpdate]
    public class ERP2WMS: AbstractOperationServicePlugIn
    {
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);
            string url = "/restcloud/wms/eai-extend-plat/processcode/InWarehouse";
            url = SystemParameterServiceHelper.GetParamter(this.Context, 1, 0, "STK_StockParameter", "F_LinkURL").ToString() + url;
            var obj = e.DataEntitys.FirstOrDefault();
            string formId = this.BusinessInfo.GetForm().Id;
            //简单生产退料申请单
            if (formId.EqualsIgnoreCase("YCVN_JDSCTLSQD"))
            {
                string billNo = obj["BillNo"].ToString();
                string fid = obj["id"].ToString();
                string createDate = obj["CreateDate"].ToString();
                //string modifyDate = obj["ModifyDate"].ToString();
                DynamicObject org = obj["StockOrgId"] as DynamicObject;
                string orgNumber = org == null ? "" : org["number"].ToString();
                var workShopID = obj["WorkShopID"] as DynamicObject;
                string wsNumber = workShopID["number"].ToString();
                DynamicObjectCollection rows = obj["Entity"] as DynamicObjectCollection;
                DynamicObject stock = rows[0]["StockID"] as DynamicObject;
                string stockNumber = stock == null ? "" : stock["number"].ToString();
                string stockIsWms = stock == null ? "" : stock["F_WMS"].ToString();
                if (stockIsWms == "01")
                {
                    YCVN_JDSCTLSQD wms = new YCVN_JDSCTLSQD();
                    wms = GetWmsObj(rows, stockNumber, orgNumber, billNo, createDate, wsNumber, fid);
                    string json = JsonConvert.SerializeObject(wms);
                    //获取同步设置和URL
                    DynamicObject setting = KAndOSysSynTool.GetKToOSysSynSetting(this.Context, "", 0);
                    //string appkey = Convert.ToString(setting["FOSysURL2"]);
                    string appkey = "657580fe4d90c676bdae626b";
                    var client = new RestClient(url);
                    client.Timeout = -1;
                    var request = new RestRequest(Method.POST);
                    request.AddHeader("appkey", appkey);
                    request.AddParameter("application/json", json, ParameterType.RequestBody);
                    IRestResponse response = client.Execute(request);
                    var res = response.Content;
                    var job = JSONObject.Parse(res);
                    if (job != null && job.ContainsKey("status") && job["status"].Equals("SUCCESS"))
                    {
                        this.OperationResult.OperateResult.Add(new Kingdee.BOS.Core.DynamicForm.OperateResult()
                        {
                            SuccessStatus = true,
                            Message = "同步WMS成功！",
                            MessageType = Kingdee.BOS.Core.DynamicForm.MessageType.Normal
                        });
                    }
                    else
                    {
                        throw new Exception("同步WMS失败，原因为：" + res + "请求报文：" + json);
                    }
                }
            }
        }

        private YCVN_JDSCTLSQD GetWmsObj(DynamicObjectCollection rows, string stockNumber, string orgNumber, string billNo, string createDate, string wsNumber, string fid)
        {
            YCVN_JDSCTLSQD wms = new YCVN_JDSCTLSQD();
            wms.projectCode = "RONMA";
            wms.processCode = "E2W_ASN";
            wms.bizData = new List<BizDataItem>();
            BizDataItem bizDataItem = new BizDataItem();
            bizDataItem.fromSystem = "ERP";
            bizDataItem.org = orgNumber;
            bizDataItem.loc = stockNumber;
            bizDataItem.receiptType = "10035";
            bizDataItem.externReceiptKey = billNo;
            bizDataItem.entryDT = createDate;
            bizDataItem.businessField06 = wsNumber;
            bizDataItem.businessField01 = fid;
            bizDataItem.asnlines = new List<AsnlinesItem>();
            wms.bizData.Add(bizDataItem);
            foreach (var row in rows)
            {
                AsnlinesItem asnlines = new AsnlinesItem();
                string lot = row["Lot_Text"] == null ? "" : row["Lot_Text"].ToString().Trim();
                asnlines.lottable06 = lot;
                //string check = "N";
                DynamicObject mat = row["MATERIALID"] as DynamicObject;
                string matNumber = mat == null ? "" : mat["number"].ToString().Trim();
                asnlines.sku = matNumber;
                asnlines.externLineNo = row["id"].ToString();
                string qty = row["Qty"].ToString();
                asnlines.qty = qty;
                DynamicObject uom = row["UnitId"] as DynamicObject;
                asnlines.uom = uom == null ? "" : uom["number"].ToString().Trim();
                asnlines.loc = stockNumber;
                DynamicObject aux = row["AuxPropId"] as DynamicObject;
                DynamicObject f2 = aux == null ? null : aux["F100002"] as DynamicObject;
                string dl = f2 == null ? "" : f2["number"].ToString().Trim();
                DynamicObject f3 = aux == null ? null : aux["F100003"] as DynamicObject;
                string ys = f3 == null ? "" : f3["number"].ToString().Trim();
                DynamicObject f4 = aux == null ? null : aux["F100004"] as DynamicObject;
                string ky = f4 == null ? "" : f4["number"].ToString().Trim();
                DynamicObject f5 = aux == null ? null : aux["F100005"] as DynamicObject;
                string tx = f5 == null ? "" : f5["number"].ToString().Trim();
                DynamicObject f6 = aux == null ? null : aux["F100006"] as DynamicObject;
                string dj = f6 == null ? "" : f6["number"].ToString().Trim();
                DynamicObject f7 = aux == null ? null : aux["F100007"] as DynamicObject;
                string xl = f7 == null ? "" : f7["number"].ToString().Trim();
                asnlines.lottable01 = xl + tx;
                asnlines.lottable02 = ys;
                asnlines.lottable07 = dj + dl;
                asnlines.businessField03 = row["id"].ToString();
                DynamicObject buom = row["BaseUnitId"] as DynamicObject;
                string buomNumber = buom == null ? "" : buom["number"].ToString();
                asnlines.businessField10 = buomNumber;

                //bool isCheck = mat["F_PXIA_CheckBox"] == null ? false : Convert.ToBoolean(mat["F_PXIA_CheckBox"]);
                //if (isCheck)
                //{
                //    check = "Y";
                //}
                asnlines.extdata = new Extdata()
                {
                    expLot06 = ky
                };
                bizDataItem.asnlines.Add(asnlines);
            }
            return wms;
        }

        /// <summary>
        /// 加载所有列
        /// </summary>
        /// <param name="e"></param>
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, this.BusinessInfo.GetForm().Id);
            var fieldKeyList = meta.BusinessInfo.GetBosFields().Select(x => x.Field.Key).ToList();
            for (int i = 0; i < fieldKeyList.Count; i++)
            {
                e.FieldKeys.Add(fieldKeyList[i]);
            }
        }
    }
}
